﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using hethongbansach.Models;
using saigonbook.Biz;

namespace hethongbansach.Models
{
    public class CartIndexViewModel
    {
        public Cart Cart { get; set; }
    }
    public class Cart
    {
        public List<CartLine> dssanpham = new List<CartLine>();

        public void AddItem(string Masp, string Tensp, int Giasanpham, int quantity)
        {
            BIZ_tonkho tk = new BIZ_tonkho();
            tk.ngay = DateTime.Now.Date;
            tk.sach = new BIZ_sach();
            tk.sach.masach = int.Parse(Masp);
            int _slcon = tk.soluongtonkho(tk);
            CartLine line = dssanpham
            .Where(p => p.masp == Masp).FirstOrDefault();
            if (line == null)
            {
                dssanpham.Add(new CartLine { masp = Masp, tensp = Tensp, giasanpham = Giasanpham, Quantity = quantity });
            }
            else
            {
                if (line.Quantity < _slcon && (line.Quantity + quantity) <= _slcon)
                {
                    line.Quantity += quantity;
                }
                else line.Quantity = _slcon;
            }
        }
        public void RemoveLine(string masp)
        {
            dssanpham.RemoveAll(l => l.masp == masp);
        }
        public decimal tongtien()
        {
            return dssanpham.Sum(e => e.giasanpham * e.Quantity);
        }
        public void capnhatsoluong(string masp, int soluong)
        {
            CartLine line = dssanpham.Where(p => p.masp == masp).FirstOrDefault();
            line.Quantity = soluong;
        }
        public void Clear()
        {
            dssanpham.Clear();
        }
        public decimal tongsanpham()
        {
            return dssanpham.Sum(e => e.Quantity);
        }
        public IEnumerable<CartLine> Lines
        {
            get { return dssanpham; }
        }

        public void save(BIZ_donhang hd)
        {
            List<BIZ_chitietdonhang> dsctdh = new List<BIZ_chitietdonhang>();
            foreach (var item in dssanpham)
            {
                BIZ_chitietdonhang cthd = new BIZ_chitietdonhang();
                cthd.donhang = new BIZ_donhang();
                cthd.donhang.madonhang = hd.madonhang;
                cthd.sach = new BIZ_sach();
                cthd.sach.masach = int.Parse(item.masp.ToString());
                cthd.soluong = item.Quantity;
                dsctdh.Add(cthd);
            }
            hd.Them_donhang(hd, dsctdh);
        }
    }
    public class CartLine
    {
        public string masp { get; set; }
        public string tensp { get; set; }
        public int giasanpham { get; set; }
        public int Quantity { get; set; }
    }

}
